/**
 * Created by apple on 17/3/18.
 */

var mysql = require('mysql');
var config = require('./config')
var pool = mysql.createPool(config);

var helper = function () {

    /**
     * 基础查询方法
     */
    this.query = function (sql, params, callback) {
        console.log(sql)
        pool.getConnection(function (err, connection) {
            // Handle error after the release.
            if (err) {
                console.log("获取链接失败 %s", err)
                throw err;
            }
            // Use the connection
            connection.query(sql, params, function (error, results, fields) {
                // And done with the connection.
                callback(results);
            });
            connection.release();
            // Don't use the connection here, it has been returned to the pool.
        });
    }

    this.insert = function (sql, params, callback) {

    }

    /**
     * 分页查询方法
     */
    this.paginate = function (countSql, countParams, querySql, queryParams, page, callback) {
        console.log(countSql)
        querySql = querySql + " limit " + page.start() + "," + page.pageSize;
        console.log("pagination", querySql);

        var data = {
            currentPage: page.pageNo, totalPages: 0
        }

        this.query(countSql, countParams, function (result) {
            if (result) {
                data.totalPages = Math.ceil(result[0].count / page.pageSize)
            }
            console.log("data", data)
            this.query(querySql, queryParams, function (error, results, fields) {
                data.datas = results
                callback(data);
            });
        }.bind(this));

    }.bind(this)
}

var page = {
    pageSize: 20,
    pageNo: 1,
    start: function () {
        return (this.pageNo - 1) * this.pageSize + 1;
    },
    total: 0,
    totalPage: 1,
}

exports.helper = helper;